const express = require('express')
const dbUser = require('./collections/dbUser')
const jwt = require('jsonwebtoken')
const crypto = require('crypto')
const multer = require('multer'); // 用于处理multipart/form-data类型的数据，常用于文件上传
const path=require('path')

const upload = multer({dest:`${path.join(__dirname,'./pablic/uploads')}`}); // 文件将保存在uploads/目录下

const routers = express.Router()

const { updateFile } = require('./controllers/uploadFile')
const { userAmend } = require('./controllers/user')

const cachedResource = {
    message: "This is a cached resource",
    timestamp: new Date().toISOString(),
    linearArray: [
        { id: 1, name: 'Item 1', parentId: null },
        { id: 2, name: 'Item 2', parentId: 1 },
        { id: 3, name: 'Item 3', parentId: 1 },
        { id: 4, name: 'Item 4', parentId: 2 },
        { id: 5, name: 'Item 5', parentId: 3 },
        { id: 6, name: 'Item 6', parentId: 3 },
        { id: 7, name: 'Item 7', parentId: 4 },
        { id: 8, name: 'Item 8', parentId: 4 },
    ]
};

routers.post('/user/amend', userAmend)

routers.post('/user/register', (req, res) => {
    const { account, password } = req.body
    dbUser.create({
        account,
        password,
        token: ""
    }).then(data => {
        console.log(data)
        res.send({ code: 200 })
    }).catch(error => {
        console.log(error)
    })
})

routers.post('/user/login', (req, res) => {
    cachedResource.timestamp=new Date().toISOString()

    const { account, password } = req.body
    dbUser.find({
        account,
        password
    }).then(data => {
        if (data.length === 0) {
            res.send({ code: 2001 })
        } else {
            try {
                const jwtToken = jwt.sign({ account }, "yejiatao", { algorithm: 'HS256', expiresIn: 60 })
                dbUser.updateOne({
                    account,
                    password
                }, { $set: { token: jwtToken } }).then(data => {
                    console.log(data)
                }).catch(error => {
                    console.log(error)
                })
                res.cookie('token', jwtToken, { httpOnly: true, maxAge: 60000 })
                res.send({ code: 200 })
            } catch (error) {
                console.log(error);
                res.status(500)
                res.send(error)
            }

        }
    }).catch(err => {
        res.send(err)
    })
})

routers.post('/getUser', (req, res) => {
    dbUser.find({
        token: req.cookies.token
    }).then(subres => {
        if (subres) {
            jwt.verify(req.cookies.token, 'yejiatao', (err, decoded) => {
                if (err) {
                    res.send({ code: 202, userData: undefined })
                } else {
                    res.send({ code: 200, userData: subres })
                }
            })
        } else {
            res.send({ code: 200, userData: undefined })
        }

    })
})


routers.get('/cache', (req, res) => {
    console.log('cache');
    const etagValue = crypto.createHash('sha256').update(JSON.stringify(cachedResource)).digest('hex')
    if (req.headers['if-none-match'] === etagValue) {
        res.status(304).send();
        return
    }
    res.setHeader('ETag', etagValue)
    res.setHeader('Cache-Control', 'public');
    res.json(cachedResource);
});

routers.post('/upload',upload.single('file'),updateFile)



module.exports = routers